import store from "@/store";
import { ACCESS_TOKEN, X_ACCESS_TOKEN } from "@/store/mutation-types";
import axios from "axios";
import Vue from "vue";

function showVuetifyDialogOfError(msg) {
  const vuetifyDialog = Vue.prototype.$dialog;
  vuetifyDialog.notify.error(msg, {
    position: "top-right",
    timeout: 6000, // 设置超时时间
  });
}

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10000, // 请求超时时间
});

// 异常的处理
const err = (error) => {
  if (error.response) {
    const data = error.response.data;
    const token = Vue.ls.get(ACCESS_TOKEN);
    if (error.response.status === 403) {
      showVuetifyDialogOfErrorr("服务器403啦，要重新登录！");
    }
    if (error.response.status === 500) {
      if (data.error.length > 0) {
        showVuetifyDialogOfError(data.error);
      }
    }
    if (error.response.status === 401) {
      showVuetifyDialogOfError("授权登录失败！");

      //如果 token 不存在就退出重新登录
      if (token) {
        store.dispatch("Logout").then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        });
      }
    }
  }
  return Promise.reject(error);
};

// request 请求拦截器
service.interceptors.request.use((config) => {
  const token = Vue.ls.get(ACCESS_TOKEN);
  const refreshToken = Vue.ls.get(X_ACCESS_TOKEN);
  if (token) {
    config.headers["Authorization"] = "Bearer " + token;
  }
  if (refreshToken) {
    config.headers["X-Authorization"] = "Bearer " + refreshToken;
  }
  return config;
}, err);

//response 响应拦截器
service.interceptors.response.use((response) => {
  if (response.headers["access-token"]) {
    Vue.ls.set(ACCESS_TOKEN, response.headers["access-token"]);
    store.commit("SET_TOKEN", response.headers["access-token"]);
  }
  if (response.headers["x-access-token"]) {
    Vue.ls.set(X_ACCESS_TOKEN, response.headers["x-access-token"]);
  }
  if (response.request.responseType === "blob") {
    return response;
  }
  const resStatus = response.status;
  const code = response.data.code;
  if (resStatus == 200 && code == 200) {
    return response;
  } else {
    if (resStatus == 401 || resStatus == 403 || code == 401 || code == 403) {
      Vue.ls.remove(ACCESS_TOKEN);
      Vue.ls.remove(X_ACCESS_TOKEN);
      store.dispatch("SetHasError", true);
    }
    showVuetifyDialogOfError(response.data.msg);
  }
}, err);

export default service;
